package my.test.csdn.weixin_43767015.basic.ch12.transaction.declarative.annotation;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@PropertySource("classpath:my/test/csdn/weixin_43767015/basic/ch12/transaction/db.properties")
@ComponentScan
@EnableAspectJAutoProxy(exposeProxy=true)
@EnableTransactionManagement
public class TransactionConfig {
	@Value("${jdbc.driverClass}")
	private String driverClassName;
	@Value("${jdbc.jdbcUrl}")
	private String url;
	@Value("${jdbc.user}")
	private String username;
	@Value("${jdbc.password}")
	private String password;

    /**
     * 配置Druid数据源
     */
	 @Bean
	 public DruidDataSource druidDataSource() {
		 DruidDataSource druidDataSource = new DruidDataSource();
	     //为了方便，直接硬编码了，我们可以通过@Value引入外部配置，
	     //如果使用Spring boot就更简单了，直接使用@ConfigurationProperties引入外部配置
	     //简单的配置数据库连接信息，其他连接池信息采用默认配置
		 druidDataSource.setDriverClassName(driverClassName);
		 druidDataSource.setUrl(url);
		 druidDataSource.setUsername(username);
		 druidDataSource.setPassword(password);
		 return druidDataSource;
	 }
	 
	 /**
	  * 配置JdbcTemplate
	  * 直接使用spring-jdbc来操作某一个数据库，不使用其他外部数据库框架
	  */
	 @Bean
	 public JdbcTemplate jdbcTemplate() {
	    return new JdbcTemplate(druidDataSource());
	 }
	 
	 /**
	  * 配置DataSourceTransactionManager
	  * 用于管理某一个数据库的事务
	  */
	 @Bean
	 public DataSourceTransactionManager transactionManager() {
	    //传入一个数据源
	    return new DataSourceTransactionManager(druidDataSource());
	 }
}
